package com.tinem.platform.web.auth.server.client;

import com.tinem.platform.module.pojo.co.RedisKeyEnum;
import cn.hutool.core.lang.Dict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className PlatformPersistentTokenRepository
 * @description TODO
 * @site 
 * @company 
 * @create 2020-09-28 12:56
 */
@Service
public class PlatformPersistentTokenRepository implements PersistentTokenRepository {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void createNewToken(PersistentRememberMeToken token) {
        Dict dict = Dict.parse(token);
        dict.set("date",String.valueOf(dict.getDate("date").getTime()));
        redisTemplate.opsForHash().putAll(RedisKeyEnum.auth_persistent_code.getKey(token.getSeries()),dict);
        redisTemplate.expireAt(RedisKeyEnum.auth_persistent_code.getKey(token.getSeries()), token.getDate());
        redisTemplate.opsForSet().add(RedisKeyEnum.auth_persistent_index_user.getKey(token.getUsername()),token.getSeries());
    }

    @Override
    public void updateToken(String series, String tokenValue, Date lastUsed) {
        redisTemplate.opsForHash().put(RedisKeyEnum.auth_persistent_code.getKey(series), "tokenValue", tokenValue);
        redisTemplate.expireAt(RedisKeyEnum.auth_persistent_code.getKey(series), lastUsed);

    }

    @Override
    public PersistentRememberMeToken getTokenForSeries(String seriesId) {
        Dict v = Dict.parse(redisTemplate.opsForHash().entries(RedisKeyEnum.auth_persistent_code.getKey(seriesId)));
        v.set("date",new Date(v.getLong("date")));
        return v.toBean(PersistentRememberMeToken.class);
    }

    @Override
    public void removeUserTokens(String username) {
        redisTemplate.opsForSet().members(RedisKeyEnum.auth_persistent_index_user.getKey(username))
                .stream().map(series -> RedisKeyEnum.auth_persistent_code.getKey(series))
                .forEach(redisTemplate::delete);
        redisTemplate.delete(RedisKeyEnum.auth_persistent_index_user.getKey(username));
    }
}
